package com.base.app_core.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ExifInterface;
import android.media.ThumbnailUtils;
import android.view.View;
import android.widget.TextView;

import com.base.app_core.util.log.F;
import com.tencent.bugly.crashreport.CrashReport;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class ImageUtils {
    /**
     * 根据输入流获取响应的位图对象
     *
     * @param in
     * @return
     */
    public static Bitmap getBitmap(InputStream in) {
        return BitmapFactory.decodeStream(in);
    }

    /**
     * 根据输入流， 缩小比获取位图对象
     *
     * @param in
     * @param scale
     * @return
     */
    public static Bitmap getBitmap(InputStream in, int scale) {
        Bitmap _bitmap = null;
        Options _ops = new Options();
        _ops.inSampleSize = scale;
        _bitmap = BitmapFactory.decodeStream(in, null, _ops);
        return _bitmap;
    }

    /**
     * 根据指定输入的宽高，保持纵横比，缩小获取位图对象
     *
     * @param width
     * @param height
     * @return
     */
    public static Bitmap getBitmap(byte[] bytes, int width, int height) {
        Bitmap _bitmap = null;
        Options _ops = new Options();
        _ops.inJustDecodeBounds = true;
        BitmapFactory.decodeByteArray(bytes, 0, bytes.length, _ops);

        _ops.inJustDecodeBounds = false;

        int scaleX = _ops.outWidth / width;
        int scaleY = _ops.outHeight / height;
        int scale = scaleX > scaleY ? scaleX : scaleY;
        _ops.inSampleSize = scale;
        _bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, _ops);
        return _bitmap;
    }

    /**
     * 根据指定的文件路径获取位图对象
     *
     * @param path
     * @return
     */
    public static Bitmap getBitMap(String path) {
        F.j("getBitMap path=" + path);
        Bitmap bitmap = null;
        bitmap = BitmapFactory.decodeFile(path);
        return bitmap;
    }

    /**
     * 将位图保存到指定的路径
     *
     * @param path
     * @param bitmap
     * @throws IOException
     */
    public static String saveBitmap(String path, Bitmap bitmap) throws IOException {
        F.j("save Bitmap path=" + path);
        if (path != null && bitmap != null) {
            File _file = new File(path);
            // 如果文件夹不存在则创建一个新的文件
            if (!_file.exists()) {
                _file.getParentFile().mkdirs();
                _file.createNewFile();
            }
            // 创建输出流
            OutputStream write = new FileOutputStream(_file);
            // 获取文件名
            String fileName = _file.getName();
            // 取出文件的格式名
            String endName = fileName.substring(fileName.lastIndexOf(".") + 1);
            if ("png".equalsIgnoreCase(endName)) {
                // bitmap的压缩格式
                bitmap.compress(CompressFormat.PNG, 100, write);
            } else {
                bitmap.compress(CompressFormat.JPEG, 100, write);
            }
            return _file.getAbsolutePath();
        }
        return null;
    }

    /**
     * 根据路径删除图片
     *
     * @param path
     */
    public static void delImageBySDPath(String path) {
        File file = new File(path);
        if (file.exists()) {
            file.delete();
        }
    }

    /**
     * Drawable转换成InputStream
     *
     * @param d
     * @return
     */
    public static InputStream Drawable2InputStream(Drawable d) {
        Bitmap bitmap = drawable2Bitmap(d);
        return Bitmap2InputStream(bitmap);
    }

    /**
     * Drawable转换成Bitmap
     *
     * @param drawable
     * @return
     */
    public static Bitmap drawable2Bitmap(Drawable drawable) {
        Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(),
                drawable.getOpacity() != PixelFormat.OPAQUE ? Config.ARGB_8888 : Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        drawable.draw(canvas);
        return bitmap;
    }

    /**
     * bitmap 转 drawable
     *
     * @param bitmap
     * @return
     */
    public static Drawable bitmap2Drawable(Bitmap bitmap) {
        if (bitmap != null) {
            return new BitmapDrawable(bitmap);
        }
        return null;
    }

    /**
     * 将Bitmap转换成InputStream
     *
     * @param bm
     * @return
     */
    public static InputStream Bitmap2InputStream(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(CompressFormat.JPEG, 100, baos);
        InputStream is = new ByteArrayInputStream(baos.toByteArray());
        return is;
    }

    /**
     * 据指定的文件路径获取位drawble
     *
     * @param path
     * @return
     */
    public static Drawable getDrawable(String path) {
        F.j("getDrawable path=" + path);
        Bitmap bitmap = null;
        bitmap = getBitMap(path);
        if (bitmap != null) {
            return new BitmapDrawable();
        }
        return null;
    }

    /**
     * 保存drawable到SD卡
     *
     * @param path
     * @param drawable
     * @throws IOException
     */
    public static void saveDrawable2Sdcrad(String path, Drawable drawable) throws IOException {
        BitmapDrawable bd = (BitmapDrawable) drawable;
        Bitmap bm = bd.getBitmap();
        if (path != null && bm != null) {
            File _file = new File(path);
            // 如果文件夹不存在则创建一个新的文件
            if (!_file.exists()) {
                _file.getParentFile().mkdirs();
                _file.createNewFile();
            }
            // 创建输出流
            OutputStream write = new FileOutputStream(_file);
            // 获取文件名
            String fileName = _file.getName();
            // 取出文件的格式名
            String endName = fileName.substring(fileName.lastIndexOf(".") + 1);
            if ("png".equalsIgnoreCase(endName)) {
                // bitmap的压缩格式
                bm.compress(CompressFormat.PNG, 100, write);
            } else {
                bm.compress(CompressFormat.JPEG, 100, write);
            }
            if (write != null) {
                write.close();
            }
        }
    }

    public static Bitmap Bytes2Bimap(byte[] b) {
        if (b.length != 0) {
            return BitmapFactory.decodeByteArray(b, 0, b.length);
        } else {
            return null;
        }
    }

    /**
     * 计算图片的缩放值
     *
     * @param options
     * @param reqWidth
     * @param reqHeight
     * @return
     */
    private static int calculateInSampleSize(Options options, int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {

            // Calculate ratios of height and width to requested height and
            // width
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);

            // Choose the smallest ratio as inSampleSize value, this will
            // guarantee
            // a final image with both dimensions larger than or equal to the
            // requested height and width.
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;

        }

        return inSampleSize;
    }

    /**
     * 获取一张最佳图
     *
     * @param inputStream
     * @param width
     * @param height
     * @return
     */
    public static Bitmap getSmallBitmap(InputStream inputStream, int width, int height) {
        int scale = 1;
        Options options = new Options();
        if (width > 0 || height > 0) {
            // Decode image size without loading all data into memory
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new BufferedInputStream(inputStream, 16 * 1024), null, options);

            int w = options.outWidth;
            int h = options.outHeight;
            while (true) {
                if ((width > 0 && w / 2 < width) || (height > 0 && h / 2 < height)) {
                    break;
                }
                w /= 2;
                h /= 2;
                scale *= 2;
            }
        }
        // Decode with inSampleSize option
        options.inJustDecodeBounds = false;
        options.inSampleSize = scale;
        return BitmapFactory.decodeStream(new BufferedInputStream(inputStream, 16 * 1024), null, options);
    }

    /**
     * 压缩图片
     *
     * @param saveAsDir 另存为目录 如:/mnt/sdcard/com.xx.code/
     * @param imgPath   图片原来路径 如:/mnt/sdcard/DCIM/Test.jpg
     * @return 另存为图片绝对路径
     */
    public static String saveCompressBitmap(String saveAsDir, String imgPath) {
        File f = new File(imgPath);
        Bitmap bm = getSmallBitmap(imgPath);
        File file = new File(saveAsDir);
        if (!file.exists() || !file.isDirectory()) {
            file.mkdirs();
        }
        String absFilePath = saveAsDir + "_small" + f.getName();
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(absFilePath);
            bm.compress(CompressFormat.JPEG, 40, fos);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return absFilePath;
    }

    public static Bitmap getSmallBitmap(String filePath) {
        final Options options = new Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, 480, 800);
        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;

        options.inDither = false;
        options.inPurgeable = true;
        options.inInputShareable = true;
        options.inTempStorage = new byte[32 * 1024];

        File file = new File(filePath);
        FileInputStream fs = null;
        try {
            fs = new FileInputStream(file);
            if (fs != null)
                return BitmapFactory.decodeFileDescriptor(fs.getFD(), null, options);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fs != null) {
                try {
                    fs.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    // ////////////////////////////////////图片处理////////////////////////////////////////////////

    /**
     * 矩形四个圆角图片
     *
     * @param bitmap
     * @return
     */
    public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
        try {
            Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),

                    bitmap.getHeight(), Config.ARGB_8888);

            Canvas canvas = new Canvas(output);

            final Paint paint = new Paint();

            final Rect rect = new Rect(0, 0, bitmap.getWidth(),

                    bitmap.getHeight());

            final RectF rectF = new RectF(new Rect(0, 0, bitmap.getWidth(),

                    bitmap.getHeight()));

            final float roundPx = 14;

            paint.setAntiAlias(true);

            canvas.drawARGB(0, 0, 0, 0);

            paint.setColor(Color.BLACK);

            canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

            paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));

            final Rect src = new Rect(0, 0, bitmap.getWidth(),

                    bitmap.getHeight());

            canvas.drawBitmap(bitmap, src, rect, paint);

            return output;

        } catch (Exception e) {

            return bitmap;

        }

    }

    public static Bitmap getScaleRoundBitmap(Bitmap bitmap, int scaleWidth) {
        Bitmap scaleBitmap = ThumbnailUtils.extractThumbnail(bitmap, scaleWidth, scaleWidth);
        Bitmap roundBitmap = ImageUtils.toRoundBitmap(scaleBitmap);
        return roundBitmap;
    }

    /**
     * 圆形（○）头像图片
     *
     * @param bitmap
     * @return
     */
    public static Bitmap toRoundBitmap(Bitmap bitmap) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        float roundPx;
        float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom;
        if (width <= height) {
            roundPx = width / 2;
            top = 0;
            bottom = width;
            left = 0;
            right = width;
            height = width;
            dst_left = 0;
            dst_top = 0;
            dst_right = width;
            dst_bottom = width;
        } else {
            roundPx = height / 2;
            float clip = (width - height) / 2;
            left = clip;
            right = width - clip;
            top = 0;
            bottom = height;
            width = height;
            dst_left = 0;
            dst_top = 0;
            dst_right = height;
            dst_bottom = height;
        }
        Bitmap output = Bitmap.createBitmap(width, height, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect src = new Rect((int) left, (int) top, (int) right, (int) bottom);
        final Rect dst = new Rect((int) dst_left, (int) dst_top, (int) dst_right, (int) dst_bottom);
        final RectF rectF = new RectF(dst);
        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, src, dst, paint);
        return output;
    }

    public static Bitmap createBitmap(Bitmap src, Bitmap watermark, Context mContex) {
        if (src == null) {
            return null;
        }
        int w = src.getWidth();
        int h = src.getHeight();
        // float l =
        // Float.parseFloat(mContex.getResources().getString(R.string.icon_left));
        // float e =
        // Float.parseFloat(mContex.getResources().getString(R.string.icon_equle));
        float l = 2.0f;
        float e = 4.0f;
        Bitmap newb = Bitmap.createBitmap(w, h, Config.ARGB_8888);// 创建一个新的和SRC长度宽度一样的位图
        Canvas cv = new Canvas(newb);
        cv.drawBitmap(src, 0, 0, null);// 在 0，0坐标开始画入src
        Bitmap newwatermark = turnRound(watermark, src.getWidth() - e);
        cv.drawBitmap(newwatermark, l, l, null);
        cv.save(Canvas.ALL_SAVE_FLAG);// 保存
        cv.restore();// 存储
        return newb;
    }

    public static Bitmap turnRound(Bitmap bitmap, float mWidth) {
        float w = bitmap.getWidth();

        Matrix matrix = new Matrix();
        float f = mWidth / w;
        matrix.postScale(f, f);

        Bitmap newBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        int width = newBitmap.getWidth();
        int height = newBitmap.getHeight();
        float roundPx;
        float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom;
        if (width <= height) {
            roundPx = width / 2;
            top = 0;
            bottom = width;
            left = 0;
            right = width;
            height = width;
            dst_left = 0;
            dst_top = 0;
            dst_right = width;
            dst_bottom = width;
        } else {
            roundPx = height / 2;
            float clip = (width - height) / 2;
            left = clip;
            right = width - clip;
            top = 0;
            bottom = height;
            width = height;
            dst_left = 0;
            dst_top = 0;
            dst_right = height;
            dst_bottom = height;
        }

        Bitmap output = Bitmap.createBitmap(width, height, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        final Paint paint = new Paint();
        final Rect src = new Rect((int) left, (int) top, (int) right, (int) bottom);
        final Rect dst = new Rect((int) dst_left, (int) dst_top, (int) dst_right, (int) dst_bottom);
        final RectF rectF = new RectF(dst);

        paint.setAntiAlias(true);

        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(Color.WHITE);
        paint.setStrokeWidth(4);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(newBitmap, src, dst, paint);

        return output;
    }

    public static Bitmap setRoundBitmapWrite(Context context, int filename) {
        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), filename);
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        float roundPx;
        float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom;
        if (width <= height) {
            roundPx = width / 2;
            top = 0;
            bottom = width;
            left = 0;
            right = width;
            height = width;
            dst_left = 0;
            dst_top = 0;
            dst_right = width;
            dst_bottom = width;
        } else {
            roundPx = height / 2;
            float clip = (width - height) / 2;
            left = clip;
            right = width - clip;
            top = 0;
            bottom = height;
            width = height;
            dst_left = 0;
            dst_top = 0;
            dst_right = height;
            dst_bottom = height;
        }

        Bitmap output = Bitmap.createBitmap(width, height, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        final Paint paint = new Paint();
        final Rect src = new Rect((int) left, (int) top, (int) right, (int) bottom);
        final Rect dst = new Rect((int) dst_left, (int) dst_top, (int) dst_right, (int) dst_bottom);
        final RectF rectF = new RectF(dst);

        paint.setAntiAlias(true);

        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(Color.WHITE);
        paint.setStrokeWidth(4);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, src, dst, paint);

        // 画白色圆圈
        paint.reset();

        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(8);
        paint.setAntiAlias(true);
        canvas.drawCircle(width / 2, width / 2, width / 2 - 8 / 2, paint);

        return output;
    }

    public static void setDrawableLeft(Drawable leftDrawable, View mView) {
        if (mView instanceof TextView) {
            TextView mTextView = (TextView) mView;
            leftDrawable.setBounds(0, 0, leftDrawable.getMinimumWidth(), leftDrawable.getMinimumHeight());
            mTextView.setCompoundDrawables(leftDrawable, null, null, null);
        }

    }

    public static void setDrawableRight(Drawable rightDrawable, TextView mView) {
        if (mView instanceof TextView && rightDrawable != null) {
            TextView mTextView = mView;
            rightDrawable.setBounds(0, 0, rightDrawable.getMinimumWidth(), rightDrawable.getMinimumHeight());
            mTextView.setCompoundDrawables(null, null, rightDrawable, null);
        }
    }

    /**
     * 图片压缩
     */
    public static String compressImage(String filePath, String fileName, int q) throws FileNotFoundException {
        Bitmap bm = null;
        try {
            bm = getSmallBitmap(filePath);
            int degree = readPictureDegree(filePath);
            if (degree != 0) {//旋转照片角度
                bm = rotateBitmap(bm, degree);
            }

            File outputFile = new File(fileName);
            if (outputFile.exists())
                outputFile.delete();
            FileOutputStream out = new FileOutputStream(outputFile);
            bm.compress(CompressFormat.JPEG, q, out);
            return outputFile.getPath();
        } catch (Exception e) {
            e.printStackTrace();
            CrashReport.postCatchedException(e);
            return null;
        } finally {
            if (bm != null) {
                bm.recycle();
            }
            bm = null;
            System.gc();
        }
    }

    public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    public static Bitmap rotateBitmap(Bitmap bitmap, int degress) {
        if (bitmap != null) {
            Matrix m = new Matrix();
            m.postRotate(degress);
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                    bitmap.getHeight(), m, true);
            return bitmap;
        }
        return bitmap;
    }

    // 缩放图片
    public static void zoomImg(String img, int newWidth, int newHeight) {
        // 图片源
        Bitmap bm = BitmapFactory.decodeFile(img);
        if (null != bm) {
            Bitmap newbm = zoomImg(bm, newWidth, newHeight);
            if (newbm != null) {
                try {
                    saveBitmap(img, newbm);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    // 缩放图片
    public static Bitmap zoomImg(Bitmap bm, int newWidth, int newHeight) {
        // 获得图片的宽高
        int width = bm.getWidth();
        int height = bm.getHeight();
        // 计算缩放比例
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 取得想要缩放的matrix参数
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // 得到新的图片
        Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
        return newbm;
    }

    public static void deleteCacheImage(String path2) {//
        File file = new File(path2);
        if (file.exists() && file.isFile()) file.delete();
    }
}
